package com.wx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.wx.Exception.SystemException;
import com.wx.Result.ResultCodeEnum;
import com.wx.constant.WxLoginConstants;
import com.wx.entity.User;
import com.wx.entity.table.UserTableDef;
import com.wx.mapper.UserMapper;
import com.wx.service.UserService;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 *  服务层实现。
 *
 * @author Administrator
 * @since 2025-07-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService{

    @Override
    public void wxLogin(String code) {
        //请求微信服务器，获取openid的值
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", WxLoginConstants.APPID);
        paramMap.put("secret", WxLoginConstants.SECRET);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result= HttpUtil.post("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        JSONObject resultObj = JSONUtil.parseObj(result);
        String openid = resultObj.getStr("openid");
        //数据库里去查openid有没有
        QueryWrapper query = new QueryWrapper();
        query.eq(User::getOpenId,openid);
        User user = getOne(query);
        //如果用户不存在就创建
        if(ObjectUtil.isEmpty(user)){
            throw new SystemException(ResultCodeEnum.NEED_LOGIN);
        }
        System.out.println(user);


    }
}
